import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/exam_question.dart';
import 'package:kxy_flutter_app/model/exam_result.dart';
import 'package:more/tuple.dart';

class ExamService {
  String userId;
  String examId;

  ExamService({
    @required this.examId,
    @required this.userId,
  });

  Future<Tuple2<int, List<Question>>> getQuestionList({String courseId}) async {
    var res = await Http.instance.post(
      '/exam-app/exam/isCanBeExam',
      params: {
        'examId': examId,
        'userId': userId,
        'otherId': courseId,
      },
    );

    if (res.code == 200) {
      return Tuple2(
        int.parse(res.data['duration']),
        (res.data['examQuesEntities'] as List).map((e) => Question.fromJson(e)).toList(),
      );
    } else {
      Fluttertoast.showToast(msg: res.msg);
      return Tuple2(0, []);
    }
  }

  Future<bool> submitAnswer(String quesId, String answer) async {
    var res = await Http.instance.post(
      '/exam-app/exam/saveQuesRecord',
      params: {
        'examId': examId,
        'quesId': quesId,
        'userId': userId,
        'selfAnsw': answer,
      },
    );
    if (res.code == 200) {
      return res.data;
    } else {
      Fluttertoast.showToast(msg: res.msg);
      return false;
    }
  }

  Future<Tuple2<bool, double>> submitPaper({String courseId}) async {
    var res = await Http.instance.post(
      '/exam-app/exam/submitPaper',
      params: {
        'examId': examId,
        'userId': userId,
        'courseId': courseId,
      },
    );

    if (res.code == 200) {
      return Tuple2(true, res.data['grade']);
    } else {
      Fluttertoast.showToast(msg: res.msg);
      return Tuple2(false, 0.0);
    }
  }

  Future<ExamResult> getExamResult() async {
    var res = await Http.instance.post(
      '/exam-app/exam/result',
      params: {
        'examId': examId,
        'userId': userId,
      },
    );

    if (res.code == 200) {
      return ExamResult.fromJson(res.data);
    } else {
      Fluttertoast.showToast(msg: res.msg);
      return null;
    }
  }

  Future collectQuestion(String quesId) async {
    var res = await Http.instance.post('/exam-app/coll/collQues', params: {
      'quesId': quesId,
      'userId': userId,
    });

    if (res.code != 200) {
      Fluttertoast.showToast(msg: res.msg);
    }
  }

  Future cancelCollectQuestion(String quesId) async {
    var res = await Http.instance.post('/exam-app/coll/unCollQues', params: {
      'quesId': quesId,
      'userId': userId,
    });

    if (res.code != 200) {
      Fluttertoast.showToast(msg: res.msg);
    }
  }
}
